<?php

namespace App\Observers;

use App\Models\Device;
use App\Models\HeartLog;
use App\Models\PhoneNumber;
use App\Models\VisitLog;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class HeartLogObserver
{
    /**
     * Handle the HeartLog "created" event.
     *
     * @param \App\Models\HeartLog $model
     * @return void
     */
    public function created(HeartLog $model)
    {
        $device = Device::query()->where(['device_id' => $model->device_id])->first();
        $device->heart_at = Carbon::now();
        $device->save();
    }

    /**
     * Handle the HeartLog "updated" event.
     *
     * @param \App\Models\HeartLog $model
     * @return void
     */
    public function updated(HeartLog $model)
    {
        //
    }

    /**
     * Handle the HeartLog "deleted" event.
     *
     * @param \App\Models\HeartLog $model
     * @return void
     */
    public function deleted(HeartLog $model)
    {
        //
    }

    /**
     * Handle the HeartLog "restored" event.
     *
     * @param \App\Models\HeartLog $model
     * @return void
     */
    public function restored(HeartLog $model)
    {
        //
    }

    /**
     * Handle the HeartLog "force deleted" event.
     *
     * @param \App\Models\HeartLog $model
     * @return void
     */
    public function forceDeleted(HeartLog $model)
    {
        //
    }

    public function creating(HeartLog $model)
    {
        $model->ip = \Illuminate\Support\Facades\Request::ip();
        //维护号码表
        $cards_json = json_decode($model->card_list, true);
        $cards_json=array_filter($cards_json);
        foreach ($cards_json as $card) {
            unset($card['cardNumber']);
            $phone_number = PhoneNumber::query()->firstOrNew($card);
            $phone_number->device_id = $model->device_code;
            $phone_number->save();
        }
    }

    public function saving(HeartLog $model)
    {
        $device = Device::query()->where(['device_id' => $model->device_id])->firstOrFail();
        $model->device_code = $device->code;
    }
    public function saved(HeartLog $model){
        if($model->device){
            $model->device->soc=$model->soc;
            $model->device->save();
        }

    }
}
